//
//  XXPlayView.m
//  you
//
//  Created by seven on 16/5/30.
//  Copyright © 2016年 seven. All rights reserved.
//

#import "XXPlayView.h"
#import "XXPlayBottomView.h"

typedef enum : NSUInteger {
    XXPlayStateUnPlay,// 未播放
    XXPlayStatePlaying, // 正在播放
    XXPlayStatePause, // 暂停播放
    XXPlayStateEnd,// 播放停止
} XXPlayState ;


@interface XXPlayView () <XXPlayBottomViewClickFullScreenBtn>

@property(nonatomic ,weak ) UILabel * titleLabel  ;

@property(nonatomic ,weak ) UIButton * playBtn ;

@property(nonatomic ,weak ) XXPlayBottomView * bottomView ;

/// 顶层View
@property(nonatomic ,weak ) UIView * topView ;

 /// 播放View
@property(nonatomic ,weak ) UIView * containerView ;

@property(nonatomic,assign) XXPlayState playState ;

@property(nonatomic,strong) AVPlayer  *player ;
@property(nonatomic,strong) AVPlayerLayer *playerLayer  ;
@property(nonatomic,strong) AVPlayerItem  *playerItem ;

@property(nonatomic,assign)  CGRect playerOriginalFrame ;
@property(nonatomic,assign)  BOOL isOriginalFrame ;

@property(nonatomic ,strong ) UIView * keyWindow ;
@property(nonatomic ,strong ) UIView * playSuprView  ;


@end

@implementation XXPlayView

- (instancetype)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
    
        UIView *containerView = [[UIView alloc]init];
        [self addSubview:containerView];
        _containerView = containerView ;
        
        UIView *topView = [UIView new];
        topView.backgroundColor = [UIColor clearColor];
        [self addSubview:topView];
         _topView = topView  ;
        UITapGestureRecognizer *hiddenGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenTopViewGesture:)];
        [_topView addGestureRecognizer:hiddenGesture];
        
      
        
        UILabel *titleLabel = [[UILabel alloc]init];
        titleLabel.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
        titleLabel.numberOfLines = 2 ;
        titleLabel.lineBreakMode = NSLineBreakByCharWrapping ;
        titleLabel.textAlignment = NSTextAlignmentCenter ;
        titleLabel.textColor = [UIColor blackColor];
        titleLabel.font = [UIFont systemFontOfSize:13];
        [topView addSubview:titleLabel];
        _titleLabel = titleLabel ;
     
        UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [playBtn setBackgroundImage:[UIImage imageNamed:@"circle_play"] forState:UIControlStateNormal];
        playBtn.bounds = CGRectMake(0, 0, 32, 32);
        playBtn.tag = 1 ;
        [playBtn addTarget:self action:@selector(clickPlayButton) forControlEvents:UIControlEventTouchUpInside];
        
        [topView addSubview:playBtn];
        _playBtn = playBtn ;
        
        XXPlayBottomView *bottomView = [[XXPlayBottomView alloc]init];
        bottomView.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
        bottomView.layer.borderColor = [UIColor redColor].CGColor;
        bottomView.layer.borderWidth = 1 ;
        bottomView.delegate = self;
        [topView addSubview:bottomView];
         _bottomView = bottomView ;
        
       
        _playState = XXPlayStateUnPlay ;
    }
    
    return self;
}
- (void)clickPlayButton{

    if (_playBtn.tag == 1) { // 点击播放按钮
        _playBtn.tag = 0 ;
        [_playBtn setBackgroundImage:[UIImage imageNamed:@"circle_pause"] forState:UIControlStateNormal];
        [self play];
        _playState = XXPlayStatePlaying ;

    }else if (_playBtn.tag == 0){ // 点击暂定按钮
        _playBtn.tag = 1;
        [_playBtn setBackgroundImage:[UIImage imageNamed:@"circle_play"] forState:UIControlStateNormal];
        [self pause];
        _playState = XXPlayStatePause ;
    }
}
#pragma mark - XXPlayBottomViewClickFullScreenBtn
- (void)clickFullScreenBtn:(UIInterfaceOrientation)orientation {
  
    if (UIInterfaceOrientationLandscapeRight == orientation) {
            // 横屏
        [self setOrientationLandscapeRight];
    }else if (UIInterfaceOrientationPortrait == orientation){
            // 竖屏
        [self setOrientationPortrait];
    }
}

/// 选择一个播放时间
- (void)seektoTime:(float)value {
    CMTime currentCMTime = CMTimeMake(value * self.bottomView.totalTime, 1);
    [self.player seekToTime:currentCMTime completionHandler:^(BOOL finished) {
        [self.player play];
    }];
    
}
- (void) setOrientationLandscapeRight {
    [self.keyWindow addSubview:self];
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationLandscapeRight;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
    [UIView animateWithDuration:0.5 animations:^{
        self.transform = CGAffineTransformMakeRotation(M_PI_2);
        self.frame = self.keyWindow.bounds;
    }];
    [self setStatusBarHidden:YES];
    
    
}

- (void) setOrientationPortrait {
    [self.playSuprView addSubview:self];
    
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
    [UIView animateWithDuration:0.5 animations:^{
        self.transform = CGAffineTransformMakeRotation(0) ;
        self.frame = self.playerOriginalFrame ;
    } completion:^(BOOL finished) {
        NSLog(@"playView.frame = %@ ",NSStringFromCGRect(self.frame));
    }];
    
    [self setStatusBarHidden:NO];
 
   
}
- (void)setStatusBarHidden:(BOOL)hidden {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    statusBar.hidden = hidden;
}

    /// 开始播放
- (void) play {
    [self.player play];
}
    ///  暂定播放
- (void) pause {
    [self.player pause];
}
- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (!_isOriginalFrame) {
        _playerOriginalFrame = self.frame ;
        self.playSuprView = self.superview ;
    }
    _containerView .frame = self.bounds ;
    self.playerLayer.frame = _containerView.bounds ;
    _topView.frame = self.bounds ;
    
    _titleLabel.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), XXTitleHeight );
    
    _playBtn.center = _topView.center ;

    _bottomView .frame = CGRectMake(0, CGRectGetHeight(self.bounds) - 35 , CGRectGetWidth(self.bounds), 35);
    _isOriginalFrame = YES ;
}

- (void)setTitleStr:(NSString *)titleStr {
    _titleStr = titleStr ;
    _titleLabel.text = titleStr ;
}
- (void)setVideoUrl:(NSURL *)videoUrl {
    _videoUrl = videoUrl ;
    self.playerItem = [AVPlayerItem playerItemWithURL:videoUrl];
    
    [self.player replaceCurrentItemWithPlayerItem:self.playerItem];
    
    [self.containerView.layer addSublayer:self.playerLayer];
    [self setNeedsLayout];
}
#pragma mark - 隐藏TopView 
- (void)hiddenTopViewGesture:(UIGestureRecognizer *) gesture {
    
    if (_playState == XXPlayStateUnPlay) {
        [self.playBtn sendActionsForControlEvents:UIControlEventTouchUpInside];
    }
    _titleLabel.hidden = !_titleLabel.hidden;
    _bottomView.hidden = !_bottomView.hidden;
    _playBtn.hidden = !_playBtn.hidden ;
    NSLog(@"click TopView ");
    
}

+(CGFloat)heightRatio {
    
    return XXScreenWidth  * 9 / 16 ;
}

- (UIImage *)thumbilImage {
    AVAsset *asset = [AVAsset assetWithURL:_videoUrl];
    AVAssetImageGenerator *assetImageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
    CGImageRef imgRef = [assetImageGenerator copyCGImageAtTime:kCMTimeZero actualTime:NULL error:nil];
    UIImage *image = [UIImage imageWithCGImage:imgRef];
    return  image;
}
#pragma mark -  懒加载
-  (UIView *)keyWindow {
    if (!_keyWindow) {
        _keyWindow = [UIApplication sharedApplication].keyWindow;
    }
    return _keyWindow;
}

- (AVPlayer *)player {
    if (!_player) {
        _player = [AVPlayer playerWithPlayerItem:self.playerItem];
        [self addProgressObserver];
    }
    return _player;
}
- (AVPlayerLayer *)playerLayer {
    
    if (!_playerLayer) {
        _playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill ;
    }
    return _playerLayer;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
   
    if ([@"status" isEqualToString:keyPath]) {
        
    }else if ([@"loadedTimeRanges" isEqualToString:keyPath]){
    
    
    }


}

- (void)addObserverToPlayerItem {
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
}

- (void) addProgressObserver {
    AVPlayerItem *playerItem = self.player.currentItem ;
    __weak typeof(self) weakSelf = self;
  [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
      float current = CMTimeGetSeconds(time);
      float total = CMTimeGetSeconds(playerItem.duration);
      weakSelf.bottomView.currentTime = current ;
      weakSelf.bottomView.totalTime = total ;
      if(current){
          weakSelf.bottomView.slideValue = current / total ;
          
          if (current == total) { // complete
              
                                                                                                                               CMTime time = CMTimeMake(4, 2);
            [weakSelf.player seekToTime:time completionHandler:^(BOOL finished) {
                weakSelf.bottomView.slideValue = 0 ;
                [weakSelf.playBtn setBackgroundImage:[UIImage imageNamed:@"circle_play"] forState:UIControlStateNormal];
                weakSelf.playBtn.tag = 0 ;
                weakSelf.playBtn.hidden = NO ;
            }];
          }
          
      }
      

  }];
}
@end
